package org.yzh.web.service;

import io.github.yezhihao.netmc.session.Session;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.yzh.commons.util.DateUtils;
import org.yzh.protocol.t808.T0200;
import org.yzh.web.model.vo.DeviceInfo;
import org.yzh.web.util.GpsCoordinateUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class GpsLocationService {
    private static final Logger log = LoggerFactory.getLogger(GpsLocationService.class.getSimpleName());
    private static final String SQL_HEAD = "insert ignore into t_tms_gps_location (device_time,device_date,device_id,mobile_no,plate_no,warning_mark,status,latitude,longitude,altitude,speed,direction,map_fence_id,create_time,del_flag) values ";
    private static final String SQL = SQL_HEAD + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)";
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    public void batchInsert(List<T0200> list) {
        String now = DateUtils.DATE_TIME_FORMATTER.format(LocalDateTime.now());
        Session session;
        String mobileNo, deviceId;
        int size = list.size();
        T0200 request;

        StringBuilder builder = new StringBuilder(size * 132 + 174);
        builder.append(SQL_HEAD);

        for (int i = 0; i < size; i++) {
            request = list.get(i);

            session = request.getSession();
            mobileNo = request.getSession().getClientId();
            deviceId = mobileNo;

            log.info("转换前：Latitude:{},Longitude:{}",request.getLatitude(),request.getLongitude());
            if(request.getLatitude() == 0){
                continue;
            }

            double latitude = request.getLatitude() / 1000000.00;
            double longitude = request.getLongitude() / 1000000.00;

            double[] gpsCoordinate = GpsCoordinateUtils.calWGS84toGCJ02(latitude, longitude);
            latitude = gpsCoordinate[0];
            longitude = gpsCoordinate[1];

            log.info("转换后：Latitude:{},Longitude:{}",latitude,longitude);

            builder.append('(');
            builder.append('\'').append(DateUtils.DATE_TIME_FORMATTER.format(request.getDeviceTime())).append('\'').append(',');
            builder.append('\'').append(DateUtils.DATE_TIME_FORMATTER.format(request.getDeviceTime())).append('\'').append(',');
            builder.append('\'').append(deviceId).append('\'').append(',');
            builder.append('\'').append(mobileNo).append('\'').append(',');
            builder.append('\'').append("").append('\'').append(',');
            builder.append(request.getWarnBit()).append(',');
            builder.append(request.getStatusBit()).append(',');
            builder.append(latitude).append(',');
            builder.append(longitude).append(',');
            builder.append(request.getAltitude()).append(',');
            builder.append(request.getSpeed()).append(',');
            builder.append(request.getDirection()).append(',');
            builder.append('0').append(',');
            builder.append('\'').append(now).append('\'').append(',').append('0');
            builder.append(')');
            builder.append(',');
        }

        if(!StringUtils.equals(builder,SQL_HEAD)) {

            String sql = builder.substring(0, builder.length() - 1);

            try (Connection connection = dataSource.getConnection();
                 Statement statement = connection.createStatement()) {
                int row = statement.executeUpdate(sql);
                if (row < size)
                    log.warn("批量写入存在重复的主键或唯一键,新增:{},忽略:{}", row, size - row);
            } catch (Exception e) {
                log.error(sql);
                log.error("批量写入失败", e);
            }
        }
    }
}
